package com.briup.app05.web.controller;

import com.briup.app05.bean.Account;
import com.briup.app05.service.IAccountService;
import com.briup.app05.utils.Message;
import com.briup.app05.utils.MessageUtil;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Validated
@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private IAccountService accountService;

    @GetMapping("findAll")
    public Message findAll() {
        return MessageUtil.success(accountService.findAll());
    }

    @GetMapping("findById")
    public Message findById(Long id) {
        return MessageUtil.success(accountService.findById(id));
    }

    @GetMapping("isExistAccount")
    public Message isExistAccount(String name) {
        return MessageUtil.success(accountService.findByAccount(name) != null);
    }

    @PostMapping("save")
    public Message save(@RequestParam @NotNull String name, @RequestParam @NotNull String password,
                        @ApiParam(hidden = true) @RequestHeader(value = "referer", required = false) final String referer) {
        HttpServletRequest req = ((ServletRequestAttributes) Objects.requireNonNull(
                RequestContextHolder.getRequestAttributes())).getRequest();
        Account account = new Account();
        account.setAccount(name);
        account.setPassword(password);
        account.setStatus("正常");
        account.setLoginIp(req.getRemoteAddr());
        account.setLoginTime(System.currentTimeMillis());
        account.setLoginAddress(referer);
        return MessageUtil.success(accountService.saveOrUpdate(account));
    }

    @DeleteMapping("deleteById")
    public Message deleteById(Long id) {
        accountService.deleteById(id);
        return MessageUtil.success("删除成功");
    }
}
